Range Sum Query - Immutable
Question
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
|
|
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Analysis
- 假如每次调用sumRange的时候相加会导致TLE,所以采用动态规划
- sum数组为当前脚标到脚标0的所有数字的加和,则SumRange=sum[j]-sum[i-1],
注意是i-1,因为需要包含脚标i的值
Code
|
|
Range Sum Query 2D - Immutable
Question
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
|
|
Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.
Analysis
- 二维数组dp记录当前坐标与坐标(0,0)所包含的全部的数字加和
- cal数组需要考虑到第一行与第一列的情况,从而进行计算
- 在计算sumRegion的时候需要注意最后的求和中,需要对脚标进行-1操作,不可直接通过计算面积的方式考量得出公式。
Code
|
|